//
//  CRBRotateBoxCustomSeriesVC.m
//  ChampsARotate
//
//  Created by Login.Fan on 2018/11/1.
//  Copyright © 2018 Logan.Fan. All rights reserved.
//

#import "CRBRotateBoxCustomSeriesVC.h"
#import "CRBRotateBoxCustomSearchView.h"
#import "CRBRotateBoxCustomItemCell.h"
#import "CRBBoxHomeHttp.h"

#import "CRBRotateBoxCustomChooseManage.h"

#import "CRBRotateBoxCustomTypeVC.h"
#import "CRBRotateBoxCustomAddVC.h"
#import "CRBCumtomAddView.h"

// customnavigition and pop
#import "CRBCustomAddPopView.h"
#import "CRBCustomAddNavigitionView.h"
#import "TheXXSystemAlert.h"
#import "MainDiscernSelectWatchVC.h"

@interface CRBRotateBoxCustomSeriesVC ()
<
UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate
>
@property (nonatomic, strong) UITableView *tableView; // table
@property (nonatomic, strong) NSMutableArray *dataSource; // data
@property (nonatomic, copy) NSMutableArray *searchDataSource; // data
@property (nonatomic, strong) CRBRotateBoxCustomSearchView *searchView; // search
@property (nonatomic, strong) CRBCumtomAddView *customAddView; // search
@property (nonatomic, strong) CRBCustomAddPopView *popView;
@property (nonatomic, strong) CRBCustomAddNavigitionView *customNavigiView;

@end

@implementation CRBRotateBoxCustomSeriesVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.baseNavigationView setHiddenNav:YES VC:self];

    [self initUI];
    [self initData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}

- (void)viewWillDisappear:(BOOL)animated {[super viewWillDisappear:animated];}

- (void)dealloc {}

#pragma mark - 设置界面
- (void)initUI {
        __weak __typeof(self)weakSelf = self;

    // 自定义导航栏
    _customNavigiView = [CRBCustomAddNavigitionView new];
    _customNavigiView.title.text = @"系列";
    [self.view addSubview:_customNavigiView];
    [_customNavigiView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0,*)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        }else{
            make.top.equalTo(self.view.mas_top).offset(20);
        }
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    // 底部pop箭头视图
    _popView = [CRBCustomAddPopView new];
    _popView.popBlock = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    [self.view addSubview:_popView];
    [_popView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }else{
            make.bottom.equalTo(self.view.mas_bottom).offset(0);
        }
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(64);
    }];
    [self initTableView];
}

- (void)initTableView {
  //  self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenW, H_SCREEN - 64) style:UITableViewStylePlain];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 60;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.tableFooterView = [UIView new];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.customNavigiView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.popView.mas_top).offset(0);
    }];
    
    self.searchView = [CRBRotateBoxCustomSearchView createFromXibWithFrame:CGRectZero];
    self.searchView.searchTextField.delegate = self;
    [self.searchView.searchTextField addTarget:self action:@selector(textFieldTextDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.tableView.tableHeaderView = self.searchView;
    /*
     *  如果tableview使用masonry适配，tableHeaderView也必须用masonry适配...
     */
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.height.equalTo(@60);
    }];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CRBRotateBoxCustomItemCell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
    
    [self.tableView reloadData];
}

#pragma mark - 初始化数据
- (void)initData {
    [self fetchDataFromServers];
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}
- (NSMutableArray *)searchDataSource {
    if (!_searchDataSource) {
        _searchDataSource = [[NSMutableArray alloc] init];
    }
    return _searchDataSource;
}

#pragma mark - 网络请求
- (void)fetchDataFromServers {
        __weak __typeof(self)weakSelf = self;

    NSString *brandId = [CRBRotateBoxCustomChooseManage shareManager].brandInfoModel.id;
    [CRBBoxHomeHttp requestSeriesListDataWithBrandId:brandId :^(NSURLSessionDataTask *task, id responseObject) {
        weakSelf.dataSource = (NSMutableArray *)responseObject;
        CRBSeriesInfoModel *model = [[CRBSeriesInfoModel alloc]init];
        model.seriesName = @"其他";
        model.seriesNameNative = @"其他";

        [weakSelf.dataSource  insertObject:model atIndex:0];
        weakSelf.searchDataSource = weakSelf.dataSource;
        [self updateSearchDataSource:nil];
        [weakSelf.tableView reloadData];
    } fail:^(NSURLSessionDataTask *task, NSError *error, NSString *code, NSString *msg) {
        [TheXXSystemAlert alertFrom:self alertTitle:[NSString stringWithFormat:@"%@",msg] defaultTitle:@"确定" actionType:UIAlertActionStyleDefault defaultHandler:^{
            NSLog(@"code:%@ msg:%@",[NSString stringWithFormat:@"%@",code],[NSString stringWithFormat:@"%@",msg] );
        }];
    }];
}

#pragma mark - 代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CRBRotateBoxCustomItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    
    CRBSeriesInfoModel *model = _searchDataSource[indexPath.row];
    

    [cell setSeriesInfoModel:model];
    
    
    if (_dataSource.count == _searchDataSource.count || [CRBRotateBoxCustomChooseManage shareManager].customSeriesName == nil) {
        [cell cellSelectes:([CRBRotateBoxCustomChooseManage shareManager].seriesIndexPath == indexPath)];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    
    if ([CRBRotateBoxCustomChooseManage shareManager].seriesIndexPath == indexPath && [CRBRotateBoxCustomChooseManage shareManager].goodsIndexPath) {
        [self returnAddWatchView];
        return;
    }
    
    
    CRBSeriesInfoModel *model = _searchDataSource[indexPath.row];
    NSInteger row = [_dataSource indexOfObject:model];
    NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:row inSection:0];
    
    if (indexPath.row == 0 && _dataSource.count == _searchDataSource.count) {
        [[CRBRotateBoxCustomChooseManage shareManager] saveSeriesWithIndexPath:selectedIndexPath seriesModel:model];
        [self returnAddWatchView];
        return;
    }
    
    
    // 点击这里说明画选择了列表里存在品牌，所以去除自定义品牌
    [[CRBRotateBoxCustomChooseManage shareManager] saveSeriesWithIndexPath:selectedIndexPath seriesModel:model];
    [tableView reloadData]; 

    CRBRotateBoxCustomTypeVC *vc = [[CRBRotateBoxCustomTypeVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
//    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 其他方法
/** 返回添加界面*/
- (void)returnAddWatchView {
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[MainDiscernSelectWatchVC class]]) {
//            [(MainDiscernSelectWatchVC *)vc refreshChooseView];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popToViewController:vc animated:YES];

//                [self.navigationController popToViewController:vc animated:YES complete:nil];
            });
        }
    }
}
- (void)updateSearchDataSource:(NSString *)keyword {
    if (keyword.length > 0) {
        NSMutableArray *tempDataSource = [NSMutableArray new];
        for (CRBSeriesInfoModel *model in _dataSource) {
            if ([model.seriesNameNative isEqualToString:keyword]) {
                [tempDataSource addObject:model];
            }
        }
        _searchDataSource = tempDataSource;
        
        if (_searchDataSource.count == 0) {
            // 没有搜索结果时开启手动输入系列view
            [self showCustomAddView];
            _customAddView.contentLabel.text = keyword;
        } else {
            [self dissmissCustomAddView];
        }
        
    } else if (_dataSource.count > 0){
        _searchDataSource = _dataSource;
        [self dissmissCustomAddView];
    } else if (_dataSource.count ==0) {
        // 列表一开始就没数据
        [self showCustomAddView];
    }
}
#pragma mark - textField Delegate
//监听改变方法 非delegate
- (void)textFieldTextDidChange:(UITextField *)textChange{
    NSLog(@"CRBRotateBoxCustomSeriesVC->搜索框文字：%@",textChange.text);
    [self updateSearchDataSource:textChange.text];
    [_tableView reloadData];
}
// 这个方法监听变化的一个字符，而textField.text是变化前，应用addtarget方法监听didchange
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//    if (textField.text || textField.text.length > 0) {
//        [self updateSearchDataSource:string];
//    } else {
//        _searchDataSource = _dataSource;
//    }
//    [_tableView reloadData];

    return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    //文本彻底结束编辑时调用
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    //返回BOOL值，指定是否允许文本字段结束编辑，当编辑结束，文本字段会让出第一响应者
    return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // 点击键盘的‘换行’会调用
    [textField resignFirstResponder];
    return YES;
}
#pragma mark - CustomAddView
- (void)showCustomAddView {
    if (!_customAddView) {
        _customAddView = [CRBCumtomAddView new];
        _customAddView.tipLabel.text = @"*未找到相关系列，如确认无误，可选择已输入的内容";;
        [self.view addSubview:_customAddView];
        [_customAddView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (Is_Iphone_X_Series) {
                make.top.equalTo(self.view.mas_top).offset(124 + 24);
            } else {
                make.top.equalTo(self.view.mas_top).offset(124);
            }
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(74);
        }];
            __weak __typeof(self)weakSelf = self;

        _customAddView.selectedFinishedBlock = ^(NSString *str) {
            [CRBRotateBoxCustomChooseManage shareManager].seriesIndexPath = nil;
            [CRBRotateBoxCustomChooseManage shareManager].customSeriesName = str;
            CRBRotateBoxCustomTypeVC *vc = [[CRBRotateBoxCustomTypeVC alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
//            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
    }
}
- (void)dissmissCustomAddView {
    if (_customAddView) {
        [_customAddView removeFromSuperview];
        _customAddView = nil;
    }
}

@end
